package logic

import (
	"context"
	"errors"
	"register/models/mysql"
	"register/pkg"
	"register/registerrpc/internal/svc"
	"register/registerrpc/registerrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册
func (l *RegisterLogic) Register(in *registerrpc.RegisterCaptchaRequest) (*registerrpc.RegisterCaptchaResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	err := user.UserByUsername(mysql.DB, in.UserName)
	if user.Username == in.UserName {
		return nil, errors.New("用户已存在")
	}
	user = mysql.User{
		Username: in.UserName,
		Password: pkg.Md5(in.Password),
	}
	err = user.Register(mysql.DB)
	if err != nil {
		return nil, errors.New("注册失败")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码不正确")
	}
	return &registerrpc.RegisterCaptchaResponse{
		UserName: user.Username,
		Password: user.Password,
	}, nil
}
